﻿using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using System.Xml.Serialization;
using Microsoft.Xna.Framework.Graphics;
using Urbania.GUI.Elements;
using Urbania.Utilities;

namespace Urbania.GUI
{
    [Serializable]
    [XmlRoot("Container")]
    public class GUIContainer
    {
        List<GUI.Elements.Frame> frames;
        List<GUI.Elements.Menu> menus;

        public GUIContainer()
        {
            frames = new List<Elements.Frame>();
            menus = new List<Elements.Menu>();
        }

        public void AddFrame(Elements.Frame frame)
        {
            frames.Add(frame);
        }

        public void AddMenu(Elements.Menu menu)
        {
            menus.Add(menu);
        }

        public Elements.Frame GetBaseFrame()
        {
            return frames[0];
        }

        public void DeleteMenu(Elements.Menu menu)
        {
            menus.Remove(menu);
            menu = null;
        }

        public void ClearRightClickMenus()
        {
            for(int i=0; i<menus.Count; i++)
            {
                Menu m = menus[i];
                if (m is RightClickMenu)
                {
                    DeleteMenu(m);
                }
            }
        }

        public void Update(GameTime gameTime)
        {
            for(int i = 0; i < frames.Count; i++)
                frames[i].Update(gameTime);
            for(int i = 0; i < menus.Count; i++)
                menus[i].Update(gameTime);

            if (MouseWrap.wasReleased(MouseWrap.LeftClick) || MouseWrap.wasReleased(MouseWrap.RightClick))
            {
                this.ClearRightClickMenus();
            }

            for (int i = 0; i < this.GetBaseFrame().Elements.Count; i++)
            {
                if (this.GetBaseFrame().Elements[i].toRemove)
                    this.GetBaseFrame().Elements.Remove(this.GetBaseFrame().Elements[i]);
            }


        }

        public void Draw(GameTime gameTime, SpriteBatch spriteBatch)
        {
            foreach (Elements.Frame frame in frames)
                frame.Draw(gameTime, spriteBatch);
            foreach (Elements.Menu menu in menus)
                menu.Draw(gameTime, spriteBatch);
        }
    }
}
